package com.example.androidexample.qr;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.os.Build;

import androidx.annotation.RequiresApi;

import java.io.IOException;

//蜂鸣器
public class BuzzerController implements MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {

    private MediaPlayer mediaPlayer;
    private Context context = null;
    private float beepVolume;

    public BuzzerController(Context context, float beepVolume) {
        this.context = context;
        this.beepVolume = beepVolume;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void initBuzzer() {

        AssetFileDescriptor file = context.getResources().openRawResourceFd(0);
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(),file.getStartOffset(),file.getLength());
            AudioAttributes attr = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();


            mediaPlayer.setAudioAttributes(attr);
            mediaPlayer.setLooping(false);
            //设置音量
            mediaPlayer.setVolume(beepVolume,beepVolume);
            mediaPlayer.prepare();
            mediaPlayer.setOnErrorListener(this);
            mediaPlayer.setOnCompletionListener(this);
        } catch (IOException e) {
            e.printStackTrace();
            mediaPlayer.release();
        }
    }

    public void destoryBuzzer() {
        cancelBeep();
    }

    public void playBeep() {
        mediaPlayer.start();
    }

    public void cancelBeep() {
        context = null;
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {

        } else {
            mp.release();
            mediaPlayer = null;
            initBuzzer();
        }
        return true;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mp.seekTo(0);
    }
}
